package com.youlu.campus.service.commission;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.google.common.collect.Lists;
import com.youlu.campus.entity.*;
import com.youlu.campus.entity.VO.res.ExportUserActivitySignUpRes;
import com.youlu.campus.entity.commission.DistributorChannel;
import com.youlu.campus.entity.commission.DistributorChannelActivity;
import com.youlu.campus.entity.commission.DistributorChannelSharingCommissionDetail;
import com.youlu.campus.entity.commission.UserParticipateDistributorChannelInfo;
import com.youlu.campus.entity.commission.dto.DistributorChannelCommissionOrderQueryDTO;
import com.youlu.campus.entity.commission.dto.DistributorChannelSharingCommissionOrderDTO;
import com.youlu.campus.entity.commission.dto.ExportDistributorChannelSharingCommissionDTO;
import com.youlu.campus.entity.commission.enums.SharingCommissionProfitStatus;
import com.youlu.campus.entity.course.UserCourseOrder;
import com.youlu.campus.entity.course.entity.UserKosCouponsOrder;
import com.youlu.campus.entity.enums.CourseOrderStatusEnum;
import com.youlu.campus.entity.enums.CourseOrderTypeEnum;
import com.youlu.campus.entity.enums.SharingProfitOrderTypeEnum;
import com.youlu.campus.entity.system.SystemUser;
import com.youlu.campus.service.activity.ActivityService;
import com.youlu.campus.service.activity.UserParticipateActivityInfoService;
import com.youlu.campus.service.file.FileExportTaskService;
import com.youlu.campus.service.file.FileService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.repository.support.PageableExecutionUtils;
import org.springframework.stereotype.Service;

import java.io.*;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 渠道佣金计算类
 */
@Slf4j
@Service
public class DistributorChannelSharingCommissionService {

    @Autowired
    private MongoTemplate mongoTemplate;
    /**
     * 分佣比例不能为0
     */
    public final static Double ZERO = 0d;

    @Autowired
    private DistributorChannelService distributorChannelService;

    @Autowired
    private UserParticipateDistributorChannelInfoService userParticipateDistributorChannelInfoService;
    @Lazy
    @Autowired
    private ActivityService activityService;

    @Autowired
    private DistributorChannelActivityService distributorChannelActivityService;

    @Autowired
    private DistributorChannelGmvStatisticsService distributorChannelGmvStatisticsService;

    @Autowired
    private FileExportTaskService fileExportTaskService;

    @Autowired
    private FileService fileService;

    @Autowired
    private UserParticipateActivityInfoService userParticipateActivityInfoService;

    public void initCommission(){
        log.info("【渠道分拥初始化用户信息】start ");

        List<DistributorChannelSharingCommissionDetail> list = this.mongoTemplate.find(new Query(), DistributorChannelSharingCommissionDetail.class);
        if(CollectionUtils.isEmpty(list)){
            return;
        }
        list.stream().forEach(sharingCommissionDetail -> {
            String orderNo = sharingCommissionDetail.getOrderNo();
            SharingProfitOrderTypeEnum sharingProfitOrderType = sharingCommissionDetail.getSharingProfitOrderType();
            Query query = new Query();
            query.addCriteria(Criteria.where("orderNo").is(orderNo));
            switch (sharingProfitOrderType){
                case KOS_ORDER:
                    log.info("【渠道分拥初始化用户信息】orderNo:{} type:{}",orderNo,"KOS_ORDER");
                    UserKosCouponsOrder userKosCouponsOrder = this.mongoTemplate.findOne(query, UserKosCouponsOrder.class);
                    if(Objects.nonNull(userKosCouponsOrder)){
                        sharingCommissionDetail.setUserId(userKosCouponsOrder.getUserId());
                        sharingCommissionDetail.setMobile(userKosCouponsOrder.getPhone());
                        sharingCommissionDetail.setName(userKosCouponsOrder.getName());
                        UserParticipateActivityInfo user = this.userParticipateActivityInfoService.findByUserIdActivityId(userKosCouponsOrder.getUserId(), userKosCouponsOrder.getActivityId());
                        if(Objects.nonNull(user)){
                            sharingCommissionDetail.setUniversityId(user.getUniversityId());
                            sharingCommissionDetail.setUniversityName(user.getUniversityName());
                        }
                    }
                    break;
                case VIDEO_ORDER:
                case CHU_SAI_ORDER:
                case FU_SAI_ORDER:
                case JUE_SAI_ORDER:
                    log.info("【渠道分拥初始化用户信息】orderNo:{} type:{}",orderNo,sharingProfitOrderType);
                    UserCourseOrder courseOrder = this.mongoTemplate.findOne(query, UserCourseOrder.class);
                    if(Objects.nonNull(courseOrder)){
                        sharingCommissionDetail.setUserId(courseOrder.getUserId());
                        sharingCommissionDetail.setMobile(courseOrder.getPhone());
                        sharingCommissionDetail.setName(courseOrder.getName());
                        UserParticipateActivityInfo user = this.userParticipateActivityInfoService.findByUserIdActivityId(courseOrder.getUserId(), courseOrder.getActivityId());
                        if(Objects.nonNull(user)){
                            sharingCommissionDetail.setUniversityId(user.getUniversityId());
                            sharingCommissionDetail.setUniversityName(user.getUniversityName());
                        }
                    }
                    break;
                case PAPER_CA_ORDER:
                    log.info("【渠道分拥初始化用户信息】orderNo:{} type:{}",orderNo,"PAPER_CA_ORDER");
                    OrderInfo order = this.mongoTemplate.findOne(query, OrderInfo.class);
                    if(Objects.nonNull(order)){
                        sharingCommissionDetail.setUserId(order.getAccountInfoId());
                        sharingCommissionDetail.setMobile(order.getMobile());
                        sharingCommissionDetail.setName(order.getName());
                        sharingCommissionDetail.setUniversityId(order.getUniversityId());
                        sharingCommissionDetail.setUniversityName(order.getUniversityName());
                    }
                    break;
                case DIGITAL_CA_ORDER:
                    log.info("【渠道分拥初始化用户信息】orderNo:{} type:{}",orderNo,"DIGITAL_CA_ORDER");
                    DigitalCaOrder digitalCaOrder = this.mongoTemplate.findOne(query, DigitalCaOrder.class);
                    if(Objects.nonNull(digitalCaOrder)){
                        sharingCommissionDetail.setUserId(digitalCaOrder.getUserId());
                        sharingCommissionDetail.setMobile(digitalCaOrder.getMobile());
                        sharingCommissionDetail.setName(digitalCaOrder.getName());
                        sharingCommissionDetail.setUniversityId(digitalCaOrder.getUniversityId());
                        sharingCommissionDetail.setUniversityName(digitalCaOrder.getUniversityName());
                    }
                    break;
                    default:
            }
            Update update  = new Update();
            if(StringUtils.isNotBlank(sharingCommissionDetail.getUserId())){
                update.set("userId",sharingCommissionDetail.getUserId());
            }
            if(StringUtils.isNotBlank(sharingCommissionDetail.getName())){
                update.set("name",sharingCommissionDetail.getName());
            }
            if(StringUtils.isNotBlank(sharingCommissionDetail.getMobile())){
                update.set("mobile",sharingCommissionDetail.getMobile());
            }
            if(StringUtils.isNotBlank(sharingCommissionDetail.getUniversityId())){
                update.set("universityId",sharingCommissionDetail.getUniversityId());
            }
            if(StringUtils.isNotBlank(sharingCommissionDetail.getUniversityName())){
                update.set("universityName",sharingCommissionDetail.getUniversityName());
            }
            this.mongoTemplate.updateMulti(query,update,DistributorChannelSharingCommissionDetail.class);
        });
        log.info("【渠道分拥初始化用户信息】end ");
    }


    public void exportOrder(DistributorChannelCommissionOrderQueryDTO dto) {
        String optUserName = dto.getOptUserName();
        log.info("【渠道分销订单导出】start 导出 optUserName:{}", optUserName);
        Integer pageNo = 1;
        Integer pageSize = 2000;
        Boolean createFileTask = Boolean.FALSE;
        List<DistributorChannelSharingCommissionDetail> exportDistributorChannelOrderList = null;
        List<ExportDistributorChannelSharingCommissionDTO> exportResult = Lists.newLinkedList();
        String fileExportTaskId = "";
        String fileName = "";
        while (true){
            dto.setPageNo(pageNo);
            dto.setPageSize(pageSize);
            log.info("【渠道分销订单导出】查询第几页 page:{} 导出 optUserName:{}",pageNo, optUserName);
            Page<DistributorChannelSharingCommissionDetail> listPage = this.list(dto);
            exportDistributorChannelOrderList = listPage.getContent();
            if (CollectionUtils.isEmpty(exportDistributorChannelOrderList)) {
                log.info("【渠道分销订单导出】end 导出 optUserName:{}", optUserName);
                break;
            }
            if (!createFileTask) {
                log.info("【渠道分销订单导出】 创建文件导出任务 optUserName:{}", optUserName);
                FileExportTask fileExportTask = new FileExportTask();
                fileExportTask.setToken(optUserName);
                fileExportTask.setBizType("distributor-channel-order");
                fileExportTask.setStatus(0);
                fileExportTask.setOptUser(optUserName);
                fileExportTask.setOptUserId(dto.getOptUserId());
                fileName = "渠道分销订单明细-" + System.currentTimeMillis() + ".xlsx";
                fileExportTask.setFileName(fileName);
                fileExportTask.setNum((int) listPage.getTotalElements());
                fileExportTask.setDesc("渠道分销订单明细");
                fileExportTaskId = fileExportTaskService.create(fileExportTask);
                createFileTask = Boolean.TRUE;
            }
            //纸质证书
            List<DistributorChannelSharingCommissionDetail> paperOrderList =
                    exportDistributorChannelOrderList.stream().filter(order -> SharingProfitOrderTypeEnum.PAPER_CA_ORDER.equals(order.getSharingProfitOrderType())).collect(Collectors.toList());
            exportPaperCa(paperOrderList,exportResult);
            //电子证书
            List<DistributorChannelSharingCommissionDetail> digitalCaOderList = exportDistributorChannelOrderList.stream().filter(order -> SharingProfitOrderTypeEnum.DIGITAL_CA_ORDER.equals(order.getSharingProfitOrderType())).collect(Collectors.toList());
            exportDigitaCa(digitalCaOderList,exportResult);
            //其他信息分拥订单
            List<DistributorChannelSharingCommissionDetail> otherOrderDistributorChannelList =
                    exportDistributorChannelOrderList.stream().filter(order -> !SharingProfitOrderTypeEnum.PAPER_CA_ORDER.equals(order.getSharingProfitOrderType()) || !SharingProfitOrderTypeEnum.DIGITAL_CA_ORDER.equals(order.getSharingProfitOrderType())).collect(Collectors.toList());
            exportDistributorChannelCommissionDetail(otherOrderDistributorChannelList,exportResult);
            pageNo++;
        }
        if(CollectionUtils.isEmpty(exportResult)){
            log.info("【渠道分销订单导出】end 导出  未找到数据 optUserName:{}", optUserName);
            return;
        }
        ExcelWriter excelWriter = null;
        String file = "/data/app/file/" + fileName;
        try {
            excelWriter = EasyExcel.write(file, ExportDistributorChannelSharingCommissionDTO.class).build();
            WriteSheet writeSheet = EasyExcel.writerSheet(1, "渠道分销订单明细表").build();
            excelWriter.write(exportResult, writeSheet);
        }catch (Exception e){
            log.info("【渠道分销订单导出】end 导出 错误 optUserName:{}", optUserName,e);
        }finally {
            if (Objects.nonNull(excelWriter)) {
                excelWriter.finish();
            }
            exportResult.clear();
        }
        File newFile = new File(file);
        if (!newFile.exists()) {
            log.error("找不到渠道分销订单明细表文件");
            return;
        }
        InputStream in = null;
        try {
            in = new FileInputStream(newFile);
            String url = fileService.uploadFile(in, fileName);
            Query queryTask = new Query().addCriteria(Criteria.where("id").is(fileExportTaskId));
            Update update = new Update();
            update.set("status", 1);
            update.set("url", url);
            update.set("updatedTime", new Date());
            mongoTemplate.updateFirst(queryTask, update, FileExportTask.class);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            log.error("导出渠道分销订单明细表 error", e);
            return;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("导出渠道分销订单明细表 error", e);
            return;
        } finally {
            if (Objects.nonNull(in)) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        log.info("【渠道分销订单导出】end 导出 optUserName:{}", optUserName);
    }

    public void exportDistributorChannelCommissionDetail(List<DistributorChannelSharingCommissionDetail> otherOrderDistributorChannelList,List<ExportDistributorChannelSharingCommissionDTO> exportResult){
        if(CollectionUtils.isEmpty(otherOrderDistributorChannelList)){
            return;
        }
        log.info("【渠道分销订单导出】 其他订单数据组装 start ");
        List<String> otherOrderNoList = otherOrderDistributorChannelList.stream().map(DistributorChannelSharingCommissionDetail::getOrderNo).collect(Collectors.toList());
        Query query = new Query();
        query.addCriteria(Criteria.where("orderNo").in(otherOrderNoList));
        List<UserCourseOrder> userCourseOrderList = this.mongoTemplate.find(query, UserCourseOrder.class);
        if(CollectionUtils.isEmpty(userCourseOrderList)){
            log.info("【渠道分销订单导出】 其他订单数据组装 end ");
            return;
        }
        userCourseOrderList.stream().forEach(orderInfo->{
            DistributorChannelSharingCommissionDetail commissionDetail = otherOrderDistributorChannelList.stream().filter(commissionOrder -> commissionOrder.getOrderNo().equals(orderInfo.getOrderNo())).findFirst().orElse(null);
            if(Objects.nonNull(commissionDetail)){
                ExportDistributorChannelSharingCommissionDTO dto = new ExportDistributorChannelSharingCommissionDTO();
                dto.setOrderNo(orderInfo.getOrderNo());
                dto.setActivityChannelName(commissionDetail.getActivityChannelName());
                dto.setActivityName(commissionDetail.getActivityName());
                dto.setPayTime(commissionDetail.getPayTime());
                dto.setOrderType(CourseOrderTypeEnum.getByType(orderInfo.getCourseOrderType()).getName());
                dto.setSharingCommissionRatio(commissionDetail.getSharingCommissionRatio());
                dto.setMobile(orderInfo.getPhone());
                dto.setName(orderInfo.getName());
                UserParticipateActivityInfo user = userParticipateActivityInfoService.findByUserIdActivityId(orderInfo.getUserId(), orderInfo.getActivityId());
                if(Objects.nonNull(user)){
                    dto.setUniversity(user.getUniversityName());
                }
                dto.setSharingCommissionStatus( SharingCommissionProfitStatus.getByValue(commissionDetail.getSharingCommissionStatus()).getMsg());
                dto.setSharingCommissionAmount(BigDecimal.valueOf(commissionDetail.getSharingCommissionAmount()).divide(BigDecimal.valueOf(100)).setScale(2,BigDecimal.ROUND_HALF_UP).toString());
                dto.setOrderAmount(BigDecimal.valueOf(commissionDetail.getOrderAmount()).divide(BigDecimal.valueOf(100)).setScale(2,BigDecimal.ROUND_HALF_UP).toString());
                if(CourseOrderStatusEnum.PAY_SUCCESS.getValue()!=orderInfo.getStatus()){
                    dto.setRefundStatus("已退款");
                }else{
                    dto.setRefundStatus("未退款");
                }
                exportResult.add(dto);
            }
        });
        otherOrderNoList.clear();
        userCourseOrderList.clear();
        log.info("【渠道分销订单导出】 其他订单数据组装 end ");
    }

    public void exportDigitaCa(List<DistributorChannelSharingCommissionDetail> digitalCaOderList,
                          List<ExportDistributorChannelSharingCommissionDTO> exportResult){
        if(CollectionUtils.isEmpty(digitalCaOderList)){
            return;
        }
        log.info("【渠道分销订单导出】 电子证书订单数据组装 start ");
        List<String> digitalCaOderNoList = digitalCaOderList.stream().map(DistributorChannelSharingCommissionDetail::getOrderNo).collect(Collectors.toList());
        Query query = new Query();
        query.addCriteria(Criteria.where("orderNo").in(digitalCaOderNoList));
        List<DigitalCaOrder> digitalCaOrderList = this.mongoTemplate.find(query, DigitalCaOrder.class);
        if(CollectionUtils.isNotEmpty(digitalCaOrderList)){
            digitalCaOrderList.stream().forEach(orderInfo->{
                DistributorChannelSharingCommissionDetail commissionDetail = digitalCaOderList.stream().filter(commissionOrder -> commissionOrder.getOrderNo().equals(orderInfo.getOrderNo())).findFirst().orElse(null);
                if(Objects.nonNull(commissionDetail)){
                    ExportDistributorChannelSharingCommissionDTO dto = new ExportDistributorChannelSharingCommissionDTO();
                    dto.setOrderNo(orderInfo.getOrderNo());
                    dto.setActivityChannelName(commissionDetail.getActivityChannelName());
                    dto.setActivityName(commissionDetail.getActivityName());
                    dto.setPayTime(commissionDetail.getPayTime());
                    dto.setOrderType("电子证书");
                    dto.setSharingCommissionRatio(commissionDetail.getSharingCommissionRatio());
                    dto.setMobile(orderInfo.getMobile());
                    dto.setName(orderInfo.getName());
                    dto.setUniversity(orderInfo.getUniversityName());
                    dto.setSharingCommissionStatus( SharingCommissionProfitStatus.getByValue(commissionDetail.getSharingCommissionStatus()).getMsg());
                    dto.setOrderAmount(BigDecimal.valueOf(commissionDetail.getOrderAmount()).divide(BigDecimal.valueOf(100)).setScale(2,BigDecimal.ROUND_HALF_UP).toString());
                    dto.setSharingCommissionAmount(BigDecimal.valueOf(commissionDetail.getSharingCommissionAmount()).divide(BigDecimal.valueOf(100)).setScale(2,BigDecimal.ROUND_HALF_UP).toString());
                    dto.setRefundStatus("未退款");
                    dto.setLevel(orderInfo.getCaLevel());
                    if(StringUtils.isNotBlank(orderInfo.getMobile())){
                        Query caQuery = new Query();
                        caQuery.addCriteria(Criteria.where("mobile").is(orderInfo.getMobile()));
                        caQuery.addCriteria(Criteria.where("activityId").is(orderInfo.getActivityId()));
                        List<UserCaRecord> caRecordList = this.mongoTemplate.find(caQuery, UserCaRecord.class);
                        if(CollectionUtils.isNotEmpty(caRecordList)){
                            UserCaRecord userCaRecord = caRecordList.stream().filter(userCa -> userCa.getLevelName().equals(orderInfo.getCaLevel())).findFirst().orElse(null);
                            if(Objects.nonNull(userCaRecord)){
                                dto.setCertificateNo(userCaRecord.getCertificateNo());
                            }
                        }
                    }
                    exportResult.add(dto);
                }
            });
            digitalCaOderNoList.clear();
            digitalCaOrderList.clear();
        }
        log.info("【渠道分销订单导出】 电子证书订单数据组装 end ");
    }

    public void exportPaperCa(List<DistributorChannelSharingCommissionDetail> paperOrderList,
                         List<ExportDistributorChannelSharingCommissionDTO> exportResult){
        if(CollectionUtils.isEmpty(paperOrderList)){
            return;
        }
        log.info("【渠道分销订单导出】 纸质订单数据组装 start ");
        List<String> paperOrderNoList = paperOrderList.stream().map(DistributorChannelSharingCommissionDetail::getOrderNo).collect(Collectors.toList());
        Query query = new Query();
        query.addCriteria(Criteria.where("orderNo").in(paperOrderNoList));
        List<OrderInfo> orderInfoList = this.mongoTemplate.find(query, OrderInfo.class);
        if(CollectionUtils.isNotEmpty(orderInfoList)){
            orderInfoList.stream().forEach(orderInfo -> {
                DistributorChannelSharingCommissionDetail commissionDetail = paperOrderList.stream().filter(commissionOrder -> commissionOrder.getOrderNo().equals(orderInfo.getOrderNo())).findFirst().orElse(null);
                if(Objects.nonNull(commissionDetail)){
                    ExportDistributorChannelSharingCommissionDTO dto = new ExportDistributorChannelSharingCommissionDTO();
                    dto.setOrderNo(orderInfo.getOrderNo());
                    dto.setActivityChannelName(commissionDetail.getActivityChannelName());
                    dto.setActivityName(commissionDetail.getActivityName());
                    dto.setPayTime(commissionDetail.getPayTime());
                    dto.setOrderType("纸质证书");
                    dto.setSharingCommissionRatio(commissionDetail.getSharingCommissionRatio());
                    dto.setName(orderInfo.getName());
                    dto.setMobile(orderInfo.getMobile());
                    dto.setUniversity(orderInfo.getUniversityName());
                    dto.setSharingCommissionStatus( SharingCommissionProfitStatus.getByValue(commissionDetail.getSharingCommissionStatus()).getMsg());
                    dto.setSharingCommissionAmount(BigDecimal.valueOf(commissionDetail.getSharingCommissionAmount()).divide(BigDecimal.valueOf(100)).setScale(2,BigDecimal.ROUND_HALF_UP).toString());
                    dto.setOrderAmount(BigDecimal.valueOf(commissionDetail.getOrderAmount()).divide(BigDecimal.valueOf(100)).setScale(2,BigDecimal.ROUND_HALF_UP).toString());
                    if(Arrays.asList("6","9").contains(orderInfo.getStatus())){
                        dto.setRefundStatus("已退款");
                    }else {
                        dto.setRefundStatus("未退款");
                    }
                    Query subQuery = new Query();
                    subQuery.addCriteria(Criteria.where("orderNo").is(orderInfo.getOrderNo()));
                    List<OOrderInfo> subOrderList = this.mongoTemplate.find(subQuery, OOrderInfo.class);
                    if(CollectionUtils.isNotEmpty(subOrderList)){
                        OOrderInfo oOrder = subOrderList.stream().filter(subOrder -> StringUtils.isNotBlank(subOrder.getCertificateNo())).findFirst().orElse(null);
                        if(Objects.nonNull(oOrder)){
                            dto.setCertificateNo(oOrder.getCertificateNo());
                            CaInfo caInfo = oOrder.getCaInfo();
                            dto.setLevel(caInfo.getLevel());
                            Query caQuery = new Query();
                            caQuery.addCriteria(Criteria.where("certificateNo").is(oOrder.getCertificateNo()));
                            caQuery.addCriteria(Criteria.where("activityId").is(oOrder.getActivityId()));
                            List<UserCaRecord> caRecordList = this.mongoTemplate.find(caQuery, UserCaRecord.class);
                            if(CollectionUtils.isNotEmpty(caRecordList)){
                                UserCaRecord userCaRecord = caRecordList.stream().filter(userCa -> userCa.getLevelName().equals(caInfo.getLevel())).findFirst().orElse(null);
                                if(Objects.nonNull(userCaRecord)){
                                    dto.setCaTime(userCaRecord.getCaTime());
                                }
                            }
                        }
                    }
                    exportResult.add(dto);
                }
            });
            orderInfoList.clear();
        }
        paperOrderNoList.clear();
        log.info("【渠道分销订单导出】 纸质订单数据组装 end ");
    }

    public Page<DistributorChannelSharingCommissionDetail> list(DistributorChannelCommissionOrderQueryDTO dto) {
        String channelId = dto.getChannelId();
        String orderNo = dto.getOrderNo();
        Integer pageNo = dto.getPageNo();
        Integer pageSize = dto.getPageSize();
        PageRequest pageRequest = PageRequest.of(pageNo - 1, pageSize);
        Query query = new Query();
        if (StringUtils.isNotBlank(orderNo)) {
            query.addCriteria(Criteria.where("orderNo").is(orderNo));
        }
        if (dto.getDistributorChannelRole()) {
            List<String> listDistributorChannel =
                    distributorChannelService.findDistributorChannelByDistributorChannelUserId(dto.getDistributorChannelUserId());
            if (CollectionUtils.isEmpty(listDistributorChannel)) {
                return PageableExecutionUtils.getPage(new ArrayList<>(), pageRequest, () -> 0);
            }
            if (StringUtils.isNotBlank(channelId)) {
                if (listDistributorChannel.contains(channelId)) {
                    query.addCriteria(Criteria.where("activityChannelId").is(channelId));
                }
            } else {
                query.addCriteria(Criteria.where("activityChannelId").in(listDistributorChannel));
            }
        } else {
            if (StringUtils.isNotBlank(channelId)) {
                query.addCriteria(Criteria.where("activityChannelId").is(channelId));
            }
        }
        if (StringUtils.isNotBlank(dto.getActivityId())) {
            query.addCriteria(Criteria.where("activityId").is(dto.getActivityId()));
        }
        Date startPayTime = dto.getStartPayTime();
        Date endPayTime = dto.getEndPayTime();
        if(Objects.nonNull(startPayTime)&&Objects.nonNull(endPayTime)){
            query.addCriteria(Criteria.where("payTime").gte(startPayTime).lte(endPayTime));
        }
        if (StringUtils.isNotBlank(dto.getUniversityId())) {
            query.addCriteria(Criteria.where("universityId").is(dto.getUniversityId()));
        }
        long count = this.mongoTemplate.count(query, DistributorChannelSharingCommissionDetail.class);
        if (count == 0) {
            return PageableExecutionUtils.getPage(new ArrayList<>(), pageRequest, () -> count);
        }
//        query.with(new Sort(Sort.Direction.DESC, "createdTime"));
        Sort sort=Sort.by(Sort.Direction.DESC, "createdTime");
        query.with(sort);
        List<DistributorChannelSharingCommissionDetail> list = this.mongoTemplate.find(query.with(pageRequest),
                DistributorChannelSharingCommissionDetail.class);
        list.stream().forEach(commissionDetail -> {
            ActivityInfo activityInfo = activityService.findOne(commissionDetail.getActivityId());
            if (Objects.nonNull(activityInfo)) {
                commissionDetail.setActivityName(activityInfo.getName());
            }
        });
        return PageableExecutionUtils.getPage(list, pageRequest, () -> count);
    }


    public Integer doSharingCommissionAmount(DistributorChannelSharingCommissionOrderDTO sharingCommissionOrderDto) {
        String activityId = sharingCommissionOrderDto.getActivityId();
        String category = sharingCommissionOrderDto.getCategory();
        String orderNo = sharingCommissionOrderDto.getOrderNo();
        Integer totalFee = sharingCommissionOrderDto.getTotalFee();
        String transactionId = sharingCommissionOrderDto.getTransactionId();
        Date payTime = sharingCommissionOrderDto.getPayTime();
        String activityChannelId = sharingCommissionOrderDto.getActivityChannelId();
        String userId = sharingCommissionOrderDto.getUserId();
        //KOS VIDEO 两类活动
        if (StringUtils.isBlank(activityChannelId)) {
            UserParticipateDistributorChannelInfo userParticipateDistributorChannelInfo =
                    userParticipateDistributorChannelInfoService.findByUserIdAndActivityIdAndChannelId(userId,
                            activityId, activityChannelId);
            if (Objects.isNull(userParticipateDistributorChannelInfo)) {
                log.error("【渠道订单分拥】该订单用户未来源渠道报名 DistributorChannelSharingCommissionService.doSharingCommissionAmount" +
                                "  " +
                                "order->{}| " +
                                "category->{}| " +
                                "分账比例|ActivityChannelId:{} ", orderNo, category,
                        activityChannelId);
                return ZERO.intValue();
            }
            activityChannelId = userParticipateDistributorChannelInfo.getActivityChannelId();
        }
        DistributorChannel distributorChannel = distributorChannelService.findById(activityChannelId);
        if (Objects.isNull(distributorChannel) || Objects.isNull(distributorChannel.getDistributorRatio()) || distributorChannel.getDistributorRatio() == 0) {
            log.error("【渠道订单分拥】订单分账比例 不能为0 渠道不存在 DistributorChannelSharingCommissionService.doSharingCommissionAmount" +
                            "  " +
                            "order->{}| " +
                            "category->{}| " +
                            "分账比例|ActivityChannelId:{} ", orderNo, category, distributorChannel.getDistributorRatio(),
                    activityChannelId);
            return ZERO.intValue();
        }
        if (StringUtils.isBlank(distributorChannel.getAccountId())) {
            log.error("【渠道订单分拥】该渠道为不属于某个人 未分配该渠道负责任 DistributorChannelSharingCommissionService" +
                            ".doSharingCommissionAmount  " +
                            "order->{}| " +
                            "category->{}| " +
                            "分账比例|ActivityChannelId:{} ", orderNo, category, distributorChannel.getDistributorRatio(),
                    activityChannelId);
        }

        DistributorChannelActivity distributorChannelActivity =
                distributorChannelActivityService.findByChannelIdAndActivityId(activityChannelId, activityId);
        if (Objects.isNull(distributorChannelActivity)) {
            log.error("【渠道订单分拥】当前获取不属于该渠道 DistributorChannelSharingCommissionService" +
                            ".doSharingCommissionAmount  " +
                            "order->{}| " +
                            "category->{}| " +
                            "分账比例|ActivityChannelId:{} ", orderNo, category, distributorChannel.getDistributorRatio(),
                    activityChannelId);
            return ZERO.intValue();
        }

        Double currentSharingCommissionRatio = distributorChannel.getDistributorRatio().doubleValue();
        try {
            BigDecimal totalAmount = new BigDecimal(totalFee);
            BigDecimal sharingProfitRatioNew = new BigDecimal(currentSharingCommissionRatio);
            BigDecimal divideRatio = sharingProfitRatioNew.divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);
            int sharingProfitAmount = totalAmount.multiply(divideRatio).intValue();
            log.info("【渠道订单分拥】DistributorChannelSharingCommissionService.doSharingCommissionAmount  order->{}| " +
                            "category->{}| ratio->{}|" +
                            " sharingProfitAmount ->{}",
                    orderNo, category, currentSharingCommissionRatio, sharingProfitAmount);
            if (sharingProfitAmount <= 0) {
                log.error("【订单分账】DistributorChannelSharingCommissionService.doSharingCommissionAmount 分账金额错误不能为0 " +
                                "order->{}| category->{}| " +
                                "ratio->{}|" +
                                " sharingProfitAmount ->{}",
                        orderNo, category, currentSharingCommissionRatio, sharingProfitAmount);
            }
            Query query = new Query();
            query.addCriteria(Criteria.where("orderNo").is(orderNo));
            boolean exists = this.mongoTemplate.exists(query, DistributorChannelSharingCommissionDetail.class);
            if (exists) {
                log.warn("【渠道订单分拥】订单已存在 orderNo:{}", orderNo);
                return ZERO.intValue();
            }

            Update update = new Update();
            update.set("activityId", activityId);
            update.set("sharingProfitOrderType", SharingProfitOrderTypeEnum.valueOf(category));
            update.set("sharingCommissionRatio", currentSharingCommissionRatio);
            update.set("orderAmount", totalFee);
            update.set("sharingCommissionAmount", sharingProfitAmount);
            update.set("activityChannelId", activityChannelId);
            update.set("activityChannelName", distributorChannel.getChannelName());
            update.set("sharingCommissionStatus", SharingCommissionProfitStatus.UNSETTLED.getValue());
            update.set("channelOwnerId", distributorChannel.getAccountId());
            SystemUser systemUser = this.mongoTemplate.findById(distributorChannel.getAccountId(), SystemUser.class);
            if (Objects.nonNull(systemUser)) {
                update.set("channelOwnerName", systemUser.getRealName());
            }
            update.set("appId", sharingCommissionOrderDto.getAppId());
            update.set("merchantId", sharingCommissionOrderDto.getMerchantId());
            update.set("merchantName", sharingCommissionOrderDto.getMerchantName());
            update.set("refund", Boolean.FALSE);
            Date now = new Date();
            update.setOnInsert("createdTime", now);
            update.set("updatedTime", now);
            update.set("transactionId", transactionId);
            update.set("payTime", payTime);
            update.set("userId", userId);
            update.set("universityId", sharingCommissionOrderDto.getUniversityId());
            update.set("universityName", sharingCommissionOrderDto.getUniversityName());
            update.set("name", sharingCommissionOrderDto.getName());
            update.set("mobile", sharingCommissionOrderDto.getMobile());
            FindAndModifyOptions findAndModifyOptions = new FindAndModifyOptions();
            findAndModifyOptions.returnNew(Boolean.TRUE);
            findAndModifyOptions.upsert(Boolean.TRUE);
            this.mongoTemplate.findAndModify(query, update, findAndModifyOptions,
                    DistributorChannelSharingCommissionDetail.class);
            distributorChannelGmvStatisticsService.doGmv(orderNo, activityId, activityChannelId, totalFee);
            return sharingProfitAmount;
        } catch (Exception e) {
            log.error("【渠道订单分拥】DistributorChannelSharingCommissionService.doSharingCommissionAmount  order->{}| " +
                            "category->{}| ratio->{} " +
                            "error",
                    orderNo, category, currentSharingCommissionRatio, e);
            return ZERO.intValue();
        }
    }
}
